const fs = require('fs-extra');
const path = require('path');
const report = require('../../models/export/report');
const PhoenixError = require('../../models/phoenix-error');
const licenses = require('../../models/license');
const middleware = require('./../middleware');
const utility = require('./../../models/utility');
const { ruleLevel } = require('../../models/rules');

function getGlobalConfig(req, res, next) {
  (async () => {
    const enabledReport = await report.hasEnabledReport();
    const testReportFormats = await report.getTestReportFormats();
    const analyzeReportFormats = await report.getAnalyzeReportFormats();

    // 合并staticAnalyzeByFiles和staticAnalyzeByRules
    const staticAnalyze = Object.keys(analyzeReportFormats).reduce((o, key) => {
      if (key === 'staticAnalyzeByFiles') {
        o.classifyBy.push('files');
      } else if (key === 'staticAnalyzeByRules') {
        o.classifyBy.push('rules');
      } else {
        throw new Error('wrong template key');
      }
      const item = analyzeReportFormats[key];
      item.formats.forEach((fmt) => o.formats.set(fmt.key, fmt));
      return o;
    }, { classifyBy: [], formats: new Map() });
    staticAnalyze.formats = [...staticAnalyze.formats.values()];
    let reportFormats = { ...testReportFormats, staticAnalyze };

    const formats = [
      {
        key: 'docx',
        label: 'Word',
      },
      {
        key: 'pdf',
        label: 'Pdf',
      },
      {
        key: 'html',
        label: 'Html',
      },
    ];
    // 代码质量报告和数据流报告写死
    reportFormats.codeQualityMeasure = { formats };
    reportFormats.dataStream = { formats };
    reportFormats.codeInstrumentation = { formats };
    const enabledReportPath = path.join(__dirname, '..', '..', 'models', 'export', 'report', 'enabled-report');
    if (fs.pathExistsSync(enabledReportPath)) {
      const enabledReportIns = utility.requireUncached(enabledReportPath);
      if (enabledReportIns.codeInstrumentationSupport()) {
        reportFormats.codeInstrumentation = { formats: testReportFormats.unitTest.formats };
      }
    }
    if (licenses.isEducationVersion(req.$license)) {
      if (!req.$license.testReport) {
        reportFormats = {};
      }
      if (req.$license.testReport.indexOf(1) < 0 && req.$license.testReport.indexOf(2) < 0) {
        delete reportFormats.unitTest;
        delete reportFormats.integrationTest;
        delete reportFormats.staticAnalyze;
      }
      if (req.$license.testReport.indexOf(3) < 0) {
        delete reportFormats.codeQualityMeasure;
      }
      if (req.$license.testReport.indexOf(4) < 0) {
        delete reportFormats.dataStream;
      }
    }
    const analyze = {
      mainLevels: [ruleLevel.mandatory, ruleLevel.required, ruleLevel.advisory],
    };
    const specs = utility.getValueByKeyPath(req.$license, 'modules.staticAnalyze.modules.certify.specs');
    // 许可证中包含QW-Q-80-18-01-2014规则集，则启用设计禁忌等级
    if (Array.isArray(specs) && specs.find((item) => item === 'QW-Q-80-18-01-2014')) {
      analyze.mainLevels.push(ruleLevel.designTaboo);
    }
    res.json({
      enabledReport,
      reportFormats,
      staticAnalyze: analyze,
    });
  })()
    .catch((err) => {
      next(new PhoenixError(err));
    });
}
/**
  * Export model definition object.
  */
module.exports = (app, prefix) => {
  const globalCfgURL = `${prefix}/global-config.json`;

  app.get(globalCfgURL, middleware.user.requireTokenUnexpired);
  app.get(globalCfgURL, middleware.user.requireAvailable);
  app.get(globalCfgURL, middleware.user.requireTester);
  app.get(globalCfgURL, middleware.license.requireLicenseExist);
  app.get(globalCfgURL, getGlobalConfig);
};
